import type { PosType, GridType } from '../types';

// 获取鼠标的坐标
export const getMousePosition = (el: Element, evt: MouseEvent) => {
  const rect = el.getBoundingClientRect();
  const x = evt.pageX - rect.x;
  const y = evt.pageY - rect.y;
  return { x, y };
}

// 获取鼠标点击是在第几排几列
export const getPoint = (girdSize: number, position: PosType) => {
  const col = position.x / girdSize;
  const row = position.y / girdSize;
  return [Math.ceil(col), Math.ceil(row)];
}

//获取开始和结束位置获取矩阵
export const getMatrix = (start: PosType, end: PosType, size: number) => {
  const datas: GridType[] = [];

  let startX = start.x,
    startY = start.y,
    endX = end.x,
    endY = end.y;

  if (startX > endX) {
    endX = start.x;
    startX = end.x;
  }

  if (startY > endY) {
    endY = start.y;
    startY = end.y;
  }

  const [endCol, endRow] = getPoint(size, { x: endX, y: endY });
  const [startCol, startRow] = getPoint(size, { x: startX, y: startY });

  for (let row = startRow; row < endRow + 1; row++) {
    for (let column = startCol; column < endCol + 1; column++) {
      datas.push({ row, column });
    }
  }
  return datas;
}
